<template>
  <div class="publish-page">
    <el-card>
        <!-- 头部区域 -->
        <template #header>
            <span>发表文章</span>
            <i class="el-icon-close" @click="isShow = true"></i>
        </template>
        <!-- 主体区域 -->
         <el-form label-width="80px" :model="form" :rules="rules" ref="form">
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="文章分类" prop="cate_id">
                <el-select v-model="form.cate_id" placeholder="请选择文章分类" style="width: 100%;">
                    <el-option v-for="item in $store.state.article.tableData" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
                <quillEditor v-model="form.content" @blur="$refs.form.validateField('content')"></quillEditor>
            </el-form-item>
            <el-form-item label="文章封面" prop="cover_img">

                <div>
                    <el-image
                    style="width: 400px;
                    height: 280px;"
                    :src="imgSrc"
                    ></el-image>
                </div>

                <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :http-request="uploadFile"
                >
                    <el-button size="small" class="uploadBtn" style="border: none; color: #5787ff; font-size: 14px; padding-left: 0px;">+ 选择封面</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button
                @click="submitForm()"
                style="background-color: #4f81ff; color: #fff;"
                >发布</el-button>
                <el-button
                class="draftBtn"
                @click="editState"
                style="background-color: #E7E7E7; color: #000; border: 1px solid #e7e7e7;"
                >存为草稿</el-button>
            </el-form-item>
         </el-form>
    </el-card>

    <!-- 关闭弹窗二次提示 -->
     <el-dialog
     :visible.sync="isShow"
     style="margin-top: 15vh; color: #000; font-weight: 600;"
     width="410px"
     >
        <template #title>
            <span class="el-icon-tishi" style="color: #4f81ff;  font-size: 24px; margin-right: 10px; vertical-align:top"></span>
            <span>提示</span>
        </template>
        <span style="color: rgba(0,0,0,0.60); font-size: 14px;margin-left: 34px; font-weight: 400;">此操作将导致文章信息丢失，是否继续？</span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" style="background-color: #EEEEEE; color: rgba(0,0,0,0.90);">取消</el-button>
            <el-button type="primary" @click="confirmClose" style="background-color: #4F81FF; color: #fff;">确认</el-button>
        </span>
     </el-dialog>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { userPublishArticle, userGetArticleInfo, userEditArticle } from '@/api/articleList'
export default {
  name: 'PublishIndex',
  data () {
    return {
      isShow: false,
      imgSrc: require('@/assets/images/cover.jpg'),
      form: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: ['blur', 'change'] },
          { min: 1, max: 30, message: '文章标题需要1~30个字符', trigger: ['blur', 'change'] }
        ],
        cate_id: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '请上传文章封面', trigger: 'blur' }
        ]
      },
      token: ''
    }
  },
  async created () {
    if (this.$store.state.article.articleEditId) {
      console.log(this.$store.state.article.articleEditId)
      const res = await userGetArticleInfo(this.$store.state.article.articleEditId)

      this.imgSrc = 'http://big-event-vue-api-t.itheima.net' + res.data.cover_img

      this.form = res.data
    } else {
    //   console.log('修改id不存在')
    }
  },
  components: {
    quillEditor
  },
  methods: {
    // 阻止el-upload的action自动提交
    uploadFile (upfile) {
      // 实例化FileReader
      const reader = new FileReader()
      //   异步读取文件内容，并返回DataURL
      reader.readAsDataURL(upfile.file)
      //   异步读取完成，触发onload事件
      reader.onload = e => {
        this.imgSrc = e.target.result
      }
      //   设置本地属性为提交的文件，方便接口调用
      this.form.cover_img = upfile.file
    },
    async submitForm () {
      await this.$refs.form.validate()
      this.form.state = this.form.state === '草稿' ? this.form.state : '已发布'

      const data = new FormData()

      if (!this.$store.state.article.articleEditId) {
        data.append('title', this.form.title)
        data.append('cate_id', this.form.cate_id)
        data.append('content', this.form.content)
        data.append('state', this.form.state)
        data.append('cover_img', this.form.cover_img)

        // 调用新增接口
        const res = await userPublishArticle(data)

        if (res.message !== '发布文章成功！') {
          this.$message.error(res.message)
          return
        }
        //   重置表单内容和页面跳转至文章列表
        this.$refs.form.resetFields()
        //   发布成功提示用户
        this.$message.success(res.message)
        this.publicCommit(false)
        // 刷新页面
        location.reload()
      } else {
        data.append('id', this.form.id)
        data.append('title', this.form.title)
        data.append('cate_id', this.form.cate_id)
        data.append('content', this.form.content)
        data.append('state', this.form.state)
        data.append('cover_img', this.form.cover_img)

        // 调用修改接口
        const res = await userEditArticle(data)

        if (res.message !== '修改文章成功!') {
          this.$message.error(res.message)
          return
        }
        //   重置表单内容
        this.$refs.form.resetFields()
        // 清空仓库的数据和页面跳转至文章列表
        this.publicCommit(true)
        //   发布成功提示用户
        this.$message.success(res.message)
      }
    },
    // 关闭发布文章页面并返回文章列表页面
    confirmClose () {
      this.isShow = false
      this.publicCommit()
    },
    // 封装公共函数
    publicCommit (flag) {
      if (flag) {
        this.$router.push('/art-list')
        this.$store.commit('article/setNavShowPublish', false)
        this.$store.commit('article/setArticleEditId', '')
      } else {
        this.$router.push('/art-list')
        this.$store.commit('article/setNavShowPublish', false)
      }
    },
    // 保存草稿状态
    editState () {
      this.form.state = '草稿'
      this.$message.success('保存草稿成功！')
    }
  }
}
</script>

<style lang="scss" scoped>
.publish-page {
    .el-card {
        ::v-deep .el-card__header {
            display: flex;
            justify-content: space-between;
            padding: 23px 30px;
            font-size: 16px;
            color: #131523;
            font-weight: 500;
            .el-icon-close:hover {
                cursor: pointer;
            }
        }
        .el-card__body {
            .el-button:focus, .el-button:hover {
                background-color: #fff;
            }
            .quill-editor {
                ::v-deep .ql-editor {
                    height: 300px;
                }
            }
            .draftBtn:hover {
                color: #000;
                border: 1px solid #e7e7e7e7;
            }
        }
    }
}

</style>
